<?php

require_once ROOT_DIR.'models/TodoList.php';
require_once ROOT_DIR.'models/Todo.php';
require_once ROOT_DIR.'models/User.php';
require_once ROOT_DIR.'models/Message.php';

class RightHelper {
	
	/**
	 * Checks if the currently logged in user is a responsible person for the given Todo or Todo id
	 * @param Todo/int $todo
	 */
	public static function checkIfResponsible($todo){
		$users = User::getUsersLinkedToTodo((is_int($todo))?$todo:$todo->getID());
		$out = false;
		$uc = count($users['users']);
		for($c = 0; $c < $uc; $c++){
			if($users['roles'][$c] == 'rP'){
				if($users['users'][$c]->getID() == $_SESSION['USER_ID']){
					$out = true; 
					break;
				}
			}
		}
		return $out;
	}
	
	/**
	 * Checks if the currently logged in user is linked with the given Todo
	 * @param Todo $todo
	 * @param boolean $direct If true only direct connections to the Todo will be checked otherwise also links to containing TodoLists
	 * 
	 * @return boolean
	 */
	public static function checkIfLinkedToTodo($todo, $direct = false){
		$users = User::getUsersLinkedToTodo((is_int($todo))?$todo:$todo->getID());
		$out = false;
		$uc = count($users['users']);
		for($c = 0; $c < $uc; $c++){
			if($users['users'][$c]->getID() == $_SESSION['USER_ID']){
				$out = true; 
				break;
			}
		}
		
		if(!$out){
			$lists = TodoList::getListsLinkedWithTodo((is_int($todo))?$todo:$todo->getID());
			$lc = count($lists);
			for($c = 0; $c < $lc; $c++){
				if($lists[$c]->getOwnerID() == $_SESSION['USER_ID'] || RightHelper::sharesList($lists[$c])){
					$out = true; 
					break;
				}
			}
		}
		
		return $out;
	}
	
	/**
	 * Checks if the currently logged in user shares the given TodoList or id
	 * @param TodoList/int $list
	 * 
	 * @return boolean
	 */
	public static function sharesList($list){
		if(is_int($list)) $list = TodoList::getList($list);
		if(!is_null($list)){
			$out = ($list->isPublic() || $list->getOwnerID() == $_SESSION['USER_ID']);
			if(!$out){
				$users = User::getUsersLinkedToList($list->getID());
				$uc = count($users);
				for($c = 0; $c < $uc; $c++){
					if($users[$c]->getID() == $_SESSION['USER_ID']){
						$out = true; 
						break;
					}
				}
			}
		}
		return $out;
	}
	
	/**
	 * Checks if the thread containing the given message is visible to the currently logged in user
	 * @param Message $msg
	 */
	public static function checkIfThreadVisible($msg){
		return ($msg->getUserID() != '' && $msg->getUserID() == $_SESSION['USER_ID'])
					|| ($msg->getAuthorID() == $_SESSION['USER_ID'])
					|| ($msg->getTodoID() != '' && RightHelper::checkIfLinkedToTodo($msg->getTodoID()))
					|| ($msg->getListID() != '' && RightHelper::sharesList($msg->getListID()))
					|| ($msg->getMessageID() != '' && RightHelper::checkIfThreadVisible(Message::getMessage($msg->getMessageID())));
	}
}

?>